from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse



# Create your views here.
from .. import models
# 数据分页需导入
from django.core.paginator import Paginator
# 导入Q对象
from django.db.models import Q

# 商品分类添加
def catesadd(request):
    if request.method == 'GET':
        # 获取所有的商品分类
        data = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
        # 分配数据
        context = {'cateslist':data}
        # 加载模板
        return render(request,'myadmin/cates/add.html',context)
    elif request.method == 'POST':
        try:
            # 执行添加
            ob = models.Cates()
            ob.name = request.POST.get('name')
            ob.pid = request.POST.get('pid')
            # 判断是否为顶级分类
            if ob.pid == '0':
                ob.path = '0,'
            else:
                # 获取当前所选的分类的path
                fob = models.Cates.objects.get(id=ob.pid)
                ob.path = fob.path+ob.pid+','
            data = models.Cates.objects.all().values()
            data1 = []
            for i in data.values():
                data1.append(i['name'])
           
            print(data1)
            # 判断分类名是否存在
            if ob.name in data1:
                return HttpResponse('<script>alert("该类名已存在");location.href="'+reverse('myadmin_cates_add')+'"</script>')
            else:
                if ob.name:
                    ob.save()
                    return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_cates_index')+'"</script>')
                else:
                    return HttpResponse('<script>alert("类名不能为空");location.href="'+reverse('myadmin_cates_add')+'"</script>')

        except:
            return HttpResponse('<script>alert("添加失败");location.href="'+reverse('myadmin_cates_add')+'"</script>')



# 商品分类列表
def catesindex(request):

    # 获取所有的商品分类
    # data = models.Cates.objects.all()
    # concat 拼接
    data = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')


    # ------------------搜索---------------------
    # 
    # 获取搜索条件和数据
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')
    if types:
        # 判断搜索的类型
        if types == "all":
            # Q 对象 <===> or   filter <====>  and
            data = data.filter(Q(name__contains = keywords))

        else:
            search = {types+'__contains':keywords}
            data = data.filter(**search)

    # ----------------数据分页-----------------------
    # 
    # 实例化分页类  参数1,获取的所有的数据对象   参数2 每页显示多少条
    paginator = Paginator(data,10)

    # 获取当前页码数 ===> ?p=n
    p = request.GET.get('p',1)
    # 获取当前页的数据
    cateslist = paginator.page(p)
    # page_range  能得到页码数的区间
    print(paginator.page_range)
    # ---------------------------------------

    # 分配数据
    context = {'cateslist':cateslist}
    return render(request,'myadmin/cates/index.html',context)




# 商品分类的删除
def catesdel(request):
    # 分类id
    cid = request.GET.get('cid')

    # 判断当前类下是否还有子类
    num = models.Cates.objects.filter(pid = cid).count()
    if num:
        # 有子类,不能删除
        return JsonResponse({'error':1,'msg':'当前类下有子类,不能删除'})
    # 确认当前类型下是否有商品发布
    data = models.Goods.objects.filter(cateid = cid).count()
    if data:
        # 有商品,不能删除
        return JsonResponse({'error':2,'msg':'当前类下有商品,不能删除'})
    # 获取分类对象
    ob = models.Cates.objects.get(id = cid)
    ob.delete()
    return JsonResponse({'error':0,'msg':'删除成功'})



# 分类的修改
def catesedit(request):

    # 根据cid获取分类对象
    ob = models.Cates.objects.get(id=request.GET.get('cid'))
    ob.name = request.GET.get('name')
    ob.save()
    return JsonResponse({'error':0,'msg':'更新成功'})
    # except:
    #     return JsonResponse({'error':1,'msg':'更新失败'})